package RunableClass;


import Alert.ChkAlert;
import Alert.MP3;
import RunableClass.useClass.Addport;

import RunableSt.authenticator;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import STOCK.*;
import java.io.File;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.Properties;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import mysql.connect;
/**
 *
 * @author javadb.com
 */
public class AlertRunnable  implements Runnable {
String symbolx;int Block[]=new int[12];
public static String[]sym=new String[12];String x ="";
    private DefaultTableModel model1;
JTable JT;

    public AlertRunnable(JTable JT) {
        this.JT = JT;
    }

    public AlertRunnable() {
        //throw new UnsupportedOperationException("Not yet implemented");
    }
                   
    /**
     * Reads text from a file line by line
     */
    public String[] readFromFile(String filename,String symbol) throws SQLException {

        
        BufferedReader bufferedReader = null;
        String xc ="";
        String ya;
       for(int i=0;i<sym.length;i++){
          // sym[i]=null;
       }
        
        try {
            //Construct the BufferedReader object
            bufferedReader = new BufferedReader(new StringReader(filename));
            String line = null;
          
            while ((line = bufferedReader.readLine()) != null) {
                  int count1 = 0;int b[] = new int[1000];int c[] =new int[1000];int count2 = 0;
                //System.out.println(line.toString());
                            String linenumber = "";
                            String y ="";
                    if(line.contains("C13_FastQuote_Main.jsp?txtSymbol="+symbol+"\"")){
                            for(int i=0;i<5;i++){
                                char xx=line.charAt(i);
                                
                                if(xx>='0'&&xx<='9'){
                                    linenumber+=line.substring(i, i+1);       
                                }        
                            } //System.out.print(linenumber);  //System.out.println(aa);
                       if(line.startsWith(linenumber)){
                        for(int i=0;i<line.length();i++){
                       char a= line.charAt(i);
                      if(a=='>'){
                          ++count1;
                         b[count1]=i;
                      }else if(a=='<'){
                           ++count2;
                          c[count2]=i;
                      }}
                   for(int i=0;i<100;i++){
                          if(b[i]!=0&&c[i]!=0){
                             if(isDigit(line.substring(b[i]+1,c[i]))){
                                 ya=line.substring(b[i]+1,c[i]);
                                 if(ya.equals(symbol)){
                                     sym[0]=ya;
                                     
                                 }
                             }
                        } }
                  //  x+="@"+y;
                    

                    for(int k=1;k<=11;k++){
                        Block[k]=Integer.parseInt(linenumber)+k;
                        
                        
                        
                    }
                     }
                   
                   
                            ////////////////////////////////////
                    // System.out.print(""+y);
                     } 
                        for(int k=1;k<=11;k++){
                       
                        if(line.startsWith(String.valueOf(Block[k])+"-->")){
                        for(int i=0;i<line.length();i++){
                       char a= line.charAt(i);
                      if(a=='>'){
                          ++count1;
                         b[count1]=i;
                      }else if(a=='<'){
                           ++count2;
                          c[count2]=i;
                      }}
                   for(int i=0;i<100;i++){
                          if(b[i]!=0&&c[i]!=0){
                             if(isDigit(line.substring(b[i]+1,c[i]))){              
                                      xc=line.substring(b[i]+1,c[i]);
                                      
                             }}
                             }

                        if((!xc.equals("XD")||!xc.equals("SP")||!xc.equals("NP")||!xc.equals("SP,NP,NC")||!xc.equals("XW")
                           ||!xc.equals("SP,NC")||!xc.equals("SP,NP")||!xc.equals("NP,NC" ))&& k==1){


                           y="NOTVALUE";
                          
                       }else{
                           y=xc;
                           
                       }
                        
                    //x+="@"+y;
                  sym[k]=y;
                
                 
                   if(k==11){
                    break;

                           }
                     //  System.out.print(y);
                     }
                        
                   
                    }
                 
 
        
            
         
            }
        }
 catch (FileNotFoundException ex) {
            Logger.getLogger(AlertRunnable.class.getName()).log(Level.SEVERE, null, ex);
        }         catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //Close the BufferedReader
            try {
                if (bufferedReader != null)
                    bufferedReader.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return sym;
    }

    /**
     * @param args the command line arguments
     */
  /*public static void main(String[] args) throws SQLException {
      ST_name st=new ST_name();
      for(int p=0;p<ST_name.st.length;p++){
     ReadData s=  new ReadData();
   readFromFile("StockFile.txt",st.getname(p));
                                    for(int o=0;o<s.sym.length;o++){
                                        System.out.print(s.sym[o]+",");
                                    }System.out.println("");
      }                
       
  }*/
    
     public static boolean isDigit(String s)   {
     boolean right = false;
      char c = 0;
      for (int index = 0; index < s.length(); index ++)  {
            c = s.charAt(index);
            if (c >= '0' || c <= '9'||c=='.')  {
            right = true;
           }
       }
      return right;
}
     static  StringBuffer     content        =   new StringBuffer(""); 
    @Override
    public void run() {
             
          for(;;){ 
              
                                      //////////////////////////////////สร้างการดึงค่าจาก URL/////////////////////////////////////////////////////////////////////////////**/
     /**/         try {
         
              int count2=1;
         String buffer;
        String url = "http://www.settrade.com/C13_MarketSummaryStockType.jsp?type=S",                                                         /**/                                                      
     /**/          proxy = "proxy.up.ac.th",                                                                                        /**/
     /**/          port = "8080",                                                                                                   /**/
     /**/          username = "up\\51286885",                                                                                       /**/
     /**/          password = "7489250721";                                                                                         /**/
     /**/                                                                                                                           /**/
     /**/       //URL autoIP = new URL("http://checkip.dyndns.org:8245/");                                                          /**/
     /**/       //System.out.println("Get URL");                                                                                    /**/
     /**/                                                                                                                           /**/
     /**/     URL server = new URL(url);                                                                                            /**/
     /**/                                                                                                                           /**/
     /**/       Authenticator.setDefault(new authenticator(                                                                         /**/
     /**/                   username,password));                                                                                    /**/
     /**/       Properties systemProperties = System.getProperties();                                                               /**/
     /**/       systemProperties.setProperty("http.proxyHost",proxy);                                                               /**/
     /**/       systemProperties.setProperty("http.proxyPort",port);                                                                /**/
     /**/       HttpURLConnection connection = (HttpURLConnection)server.openConnection();                                          /**/
     /**/      connection.connect();                                                                                                /**/
     /**/                                                                                                                           /**/
     /**/                                                                                                                           /**/
     /**/       try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"TIS-620"))) {        /**/
     /**/                                                                                                                           /**/
     /**/                                                                                                                                /**/                                                                     /**/
     /**/                content = new StringBuffer("");                                                                                                             /**/
     /**/           while((buffer = in.readLine()) != null) {                                                                     /**/  
     /**/                  count2++;                                                                                              /**/  
     /**/                                                                                                                           /**/  
     /**/                                                                                                                         /**/  
     /**/                  content.append(count2).append("-->").append(buffer).append("\n");                                      /**/
     /**/                                                                                                                         /**/      
      /**/            }                                                                                                           /**/  
      /**/      }                                                                                                                 /**/  
     /**/             } catch (IOException io){
            System.err.println("Couldn't create help URL: " + io);
        

    }   
              
 
              
              
              
            //  System.out.println(f.length()+"->"+f.exists());
          
            int countindex=0;
               
              try {
          String sqlsec="SELECT count(*) FROM `stock_ alert`";
                connect a=   new connect();
                  a.rs= a.stmt.executeQuery(sqlsec);
               a.rs.next();
                      
               countindex= Integer.parseInt(a.rs.getString(1));
             //   BrowserControl.displayURL(a.rs.getString("Link"));
           a.CloseDB();
          
       } catch (SQLException ex) {
       } DefaultTableModel model=new DefaultTableModel(Col1,0);
              if(countindex>0){
                  String arid[]=new String[countindex]; 
          String Symbol[]=new String[countindex];  
           String value[]=new String[countindex];  
           String value1[]=new String[countindex];  
              try {
          String sqlsec="SELECT * FROM `stock_ alert`";
                connect a=   new connect();
                  a.rs= a.stmt.executeQuery(sqlsec);
                  int indexarray=0;
               while(a.rs.next()){
               arid[indexarray]=a.rs.getString("id"); 
                 Symbol[indexarray]=a.rs.getString("stockname");  
                  value[indexarray]=a.rs.getString("value");  
                   value1[indexarray]=a.rs.getString("value1");  
                 ++indexarray;
                
             //   BrowserControl.displayURL(a.rs.getString("Link"));
               }
             //  javax.swing.JOptionPane.showMessageDialog(null, Symbol[0] );
               //javax.swing.JOptionPane.showMessageDialog(null, Symbol[1] );
           a.CloseDB();
        
       } catch (SQLException ex) {
       }
              
              
              for(int i=0;i<Symbol.length;i++){
                    // javax.swing.JOptionPane.showMessageDialog(null,Symbol.length );
               //javax.swing.JOptionPane.showMessageDialog(null, Symbol[1] );
        try {
              String[] Array= this.readFromFile(content.toString(),Symbol[i]);
                                   // for(int o=0;o<Array.length;o++){
                                    //    System.out.print(Array[o]+",");
                                   // }
                                      //  System.out.println("");
              int indexArray5=0;
         for(int e=0;e<Array[5].length();e++){
             if( Array[5].charAt(e)=='.'){
           indexArray5++;
             }
         }
      // for(int l=0;l<sym.length;l++){
          //if(sym[l].equals(Symbol[i])){
               //  javax.swing.JOptionPane.showMessageDialog(null,RD.sym[5] );
         //     System.out.print("->"+Array[7]);
         
         
         
         String s = Array[5]; // 
         double a1 = Double.parseDouble(s);
                           double a2 = Double.parseDouble(value[i]);   
                           double a3= Double.parseDouble(value1[i]);
          DecimalFormat myFormatter = new DecimalFormat("###.##");
      String output = myFormatter.format(a1);
        String output1 = myFormatter.format(a2);
        String output2 = myFormatter.format(a3);
                        double d = Double.parseDouble(output);
                           double d1 = Double.parseDouble(output1);   
                           double d2 = Double.parseDouble(output2);
              if(d<=d1){
                  //if(Integer.parseInt(Array[5])<=Integer.parseInt(value[i])&&Integer.parseInt(Array[5])>=Integer.parseInt(value1[i])){
                if(GetSate(Symbol[i]).equals("1")){
                MP3 MP3=new MP3(Pathsound(Symbol[i]));
                MP3.playsound();
              ChkAlert ChkAlert=  new ChkAlert(new JFrame(),true);
              ChkAlert.setIdchk(Symbol[i]);
              ChkAlert.setTitle("Alert for "+Symbol[i]);
              ChkAlert.jLabel1.setText("  |  Alert for  "+Symbol[i]+" to lower");
              ChkAlert.setVisible(true);
               // javax.swing.JOptionPane.showMessageDialog(null,"STOCK ALERT "+Symbol[i]+" Low:"+value[i]+" Up:"+value1[i]);
	        MP3.close();        
                }
              }else if(d>=d2){
                    if(GetSate(Symbol[i]).equals("1")){
                MP3 MP3=new MP3(Pathsound(Symbol[i]));
                MP3.playsound();
              ChkAlert ChkAlert=  new ChkAlert(new JFrame(),true);
              ChkAlert.setIdchk(Symbol[i]);
              ChkAlert.setTitle("Alert for "+Symbol[i]);
              ChkAlert.jLabel1.setText("  |  Alert for "+Symbol[i]+ " to upper");
              ChkAlert.setVisible(true);
               // javax.swing.JOptionPane.showMessageDialog(null,"STOCK ALERT "+Symbol[i]+" Low:"+value[i]+" Up:"+value1[i]);
	        MP3.close();        
                }
              }
               String xc[]={Array[0],Array[5],Addport.Setcolor(Array[6]).toString()};
              // System.out.println(Array[0]+"-"+Array[5]+"-"+Array[6]);
              //  System.out.println("----------------------------------------");
              model.addRow(xc); 
         //  }
              
          // System.out.println(RD.sym[0]+"-"+RD.sym[5]+"-"+RD.sym[6]);
     //  }
        } catch (SQLException ex) {
        }
              }
              
               }else{
                   String xc[]={"","",""};
              model.addRow(xc); 
              }
         JT.setModel(model);
        JT.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
       
       JT.getColumnModel().getColumn(0).setResizable(false);
        JT.getColumnModel().getColumn(0).setPreferredWidth(100);
        JT.getColumnModel().getColumn(1).setResizable(false);
        JT.getColumnModel().getColumn(1).setPreferredWidth(120);
        JT.getColumnModel().getColumn(2).setResizable(true);
       JT.getColumnModel().getColumn(2).setPreferredWidth(100);   
      
              DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
      
dtcr.setHorizontalAlignment(SwingConstants.CENTER);

        JT.getColumn("SymbolName").setCellRenderer(dtcr);
JT.getColumn("Value").setCellRenderer(dtcr);
JT.getColumn("Chg").setCellRenderer(dtcr);

            try {
                Thread.sleep(5000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
    }
    }
        
     String[] Col1 = {"SymbolName","Value","Chg"};
   
     public String Pathsound(String symbol){
      connect dbcon1=new connect();
           
            String    sqlsec1="SELECT * FROM `stock_ alert` Where stockname='"+symbol+"'";
        try {
            dbcon1.rs= dbcon1.stmt.executeQuery(sqlsec1);  
            dbcon1.rs.next();
        } catch (SQLException ex) {
            Logger.getLogger(AlertRunnable.class.getName()).log(Level.SEVERE, null, ex);
        }
          
            String x = null ;
        try {
            x = dbcon1.rs.getString("soundtype");
        } catch (SQLException ex) {
            Logger.getLogger(AlertRunnable.class.getName()).log(Level.SEVERE, null, ex);
        }
       
           
             return x;
     }
     
      public String GetSate(String symbol){
      connect dbcon1=new connect();
           
            String    sqlsec1="SELECT * FROM `stock_ alert` Where stockname='"+symbol+"'";
        try {
            dbcon1.rs= dbcon1.stmt.executeQuery(sqlsec1);  
            dbcon1.rs.next();
        } catch (SQLException ex) {
            Logger.getLogger(AlertRunnable.class.getName()).log(Level.SEVERE, null, ex);
        }
          
            String x = null ;
        try {
            x = dbcon1.rs.getString("state");
        } catch (SQLException ex) {
            Logger.getLogger(AlertRunnable.class.getName()).log(Level.SEVERE, null, ex);
        }
       
           
             return x;
     }
     
}



